package com.supermarket.service;

import com.supermarket.entity.Address;
import com.supermarket.mapper.AddressMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressService {
    
    @Resource
    private AddressMapper addressMapper;
    
    /**
     * 添加收货地址
     * 
     * @param address 地址对象
     * @return 新增地址的ID
     */
    @Transactional
    public int addAddress(Address address) {
        // 如果设置为默认地址，先将该用户的所有地址设为非默认
        if (address.getIsDefault() != null && address.getIsDefault()) {
            addressMapper.cancelDefaultAddress(address.getUserId());
        }
        
        return addressMapper.insertAddress(address);
    }
    
    /**
     * 更新收货地址
     * 
     * @param address 地址对象
     * @return 影响行数
     */
    @Transactional
    public int updateAddress(Address address) {
        // 如果设置为默认地址，先将该用户的所有地址设为非默认
        if (address.getIsDefault() != null && address.getIsDefault()) {
            addressMapper.cancelDefaultAddress(address.getUserId());
        }
        
        return addressMapper.updateAddress(address);
    }
    
    /**
     * 删除收货地址
     * 
     * @param id 地址ID
     * @return 影响行数
     */
    public int deleteAddress(Integer id) {
        return addressMapper.deleteAddress(id);
    }
    
    /**
     * 根据ID获取收货地址详情
     * 
     * @param id 地址ID
     * @return 地址对象
     */
    public Address getAddressById(Integer id) {
        return addressMapper.selectAddressById(id);
    }
    
    /**
     * 获取用户的所有收货地址
     * 
     * @param userId 用户ID
     * @return 地址列表
     */
    public List<Address> getAddressByUserId(Integer userId) {
        return addressMapper.selectAddressByUserId(userId);
    }
    
    /**
     * 获取用户的默认收货地址
     * 
     * @param userId 用户ID
     * @return 默认地址对象，如果没有默认地址则返回null
     */
    public Address getDefaultAddressByUserId(Integer userId) {
        return addressMapper.selectDefaultAddressByUserId(userId);
    }
    
    /**
     * 设置默认收货地址
     * 
     * @param id 地址ID
     * @param userId 用户ID
     * @return 影响行数
     */
    @Transactional
    public int setDefaultAddress(Integer id, Integer userId) {
        // 先将该用户的所有地址设为非默认
        addressMapper.cancelDefaultAddress(userId);
        // 再将指定地址设为默认
        return addressMapper.setDefaultAddress(id, userId);
    }
}
